'''
Created on Aug 25, 2011

@author: nktran
'''

import re
import sys
import os

from fsa import FSA
from constant import LAMBDA

def format(string):
    """
    @return: new format of the string    
    """
    if string == LAMBDA:
        string = "_lambda_"        
    return string    

def read_file(fname, delim):
    """
    Return the content of the file namely fname with the delimiter
    
    @return: content of the file
    """
    if fname not in os.listdir("."):
        print fname, 'does not exist!!!'
        sys.exit(1)        
    result = set()
    fin = open(fname, 'r')
    try:
        lines = re.split(delim, fin.read())
        for line in lines:
            if len(line.strip()) == 0: continue
            result.add(line)
    finally:
        fin.close()
    
    return result                

def parse(example, fsa):
    """
    Assume fsa is deterministic
    """
    q = fsa.start_state
    for tok in example:
        if not fsa.trans.has_key((q,tok)):
            print q, tok
            return False
        q = fsa.trans[(q, tok)]
    
    if q not in fsa.final_states:
        return False

    return True

def parse_fsa(ext):
    """
    """
    fsa = FSA()
    fsa.init(ext)
    ans = raw_input('Example need to be parsed: ')
    while True:
        example = re.split('\s+', ans)
        is_accepted = parse(example, fsa)
        if is_accepted == True:
            print ans, 'is accepted by FSA!\n'
        else:
            print ans, 'is rejected by FSA!\n'
        
        ans = raw_input('Continue....(n/example)?')
        if ans == 'n':
            break

if __name__=="__main__":
    if len(sys.argv) < 2:
        print '\n usage: python utils.py [ext]'
        sys.exit(1)
        
    parse_fsa(sys.argv[1])